const userLogin = require('../components/login')
const superagent = require('superagent')
const cheerio = require('cheerio')



async function getScheduleByWeek(agent, stu, XN, XQ, DQZC) {
  let id = ''
  let result = []
  // console.log(agent, stu, XN, XQ, DQZC)

  await agent.get('https://ehall.ecut.edu.cn/psfw/sys/pswdkbapp/*default/index.do')

  await agent.post('https://ehall.ecut.edu.cn/psfw/sys/xgpspubapp/indexmenu/getAppConfig.do?appId=5395950742020172&appName=pswdkbapp').set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8').send('appId=5395950742020172&appName=pswdkbapp').then(res => {
    id = res.body.HEADER.dropMenu[0].id;
  })


  await agent.post(`https://ehall.ecut.edu.cn/psfw/sys/funauthapp/api/changeAppRole/pswdkbapp/${id}.do`)


  await agent.post('https://ehall.ecut.edu.cn/psfw/sys/xgpspubapp/userinfo/setXgCommonAppRole.do').set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8').send(`data={"ROLEID":"${id}"}`)

  await agent.post('https://ehall.ecut.edu.cn/psfw/sys/pswdkbapp/wdkbcx/getWdkbxx.do').set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8').send(`data={"XN":"${XN}","XQ":"${XQ}","ZC":${DQZC},"SJBZ":"1"}`).then(res => {
    let r = JSON.parse(res.text);
    // console.log(r)
    r.data.forEach(e => {
      let day = e.day
      e.kcxx.forEach(ele => {
        let start, end = 0
        start = ele.SKZC.indexOf('1') + 1
        end = ele.SKZC.lastIndexOf('1') + 1

        result.push({
          sno: stu,
          courseid: ele.KCDM,
          coursename: ele.KCMC,
          addr: ele.JSDM.trim().replace(' ', ':'),
          day: day,
          from: ele.KSJC,
          to: ele.JSJC,
          start: start,
          end: end,
          xn: XN,
          xq: XQ,
          bg: ele.bg
        })
      })
    })
  })
  // console.log(result)
  return result;
}

async function getTodayInfo(agent) {
  const url = 'https://ehall.ecut.edu.cn/psfw/sys/pswdkbapp/wdkbcx/getXnxqzc.do'
  let id = '20190327165300850'
  let result = {}

  await agent.post(`https://ehall.ecut.edu.cn/psfw/sys/funauthapp/api/changeAppRole/pswdkbapp/${id}.do`)


  await agent.post('https://ehall.ecut.edu.cn/psfw/sys/xgpspubapp/userinfo/setXgCommonAppRole.do').set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8').send(`data={"ROLEID":"${id}"}`)

  await agent.post(url).set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8').send('data={}').then(res => {
    result = res.body.data
  })
  return result
}

async function getStuInfo(agent) {

  let result = {}
  await agent.get(`https://ehall.ecut.edu.cn/jsonp/userDesktopInfo.json?type=&_=${Date.now()}`).then(async function (res) {
    let {
      userDepartment,
      userId,
      userSex,
      userName
    } = res.body
    let grade = userId.substr(0, 4)

    let { DQZC } = await getTodayInfo(agent)
    result = { userId, userName, userDepartment, grade, userSex, DQZC }
  })
  return result
}

// async function getScore(agent, stu, xn, xq) {

//   const url = `https://172-20-130-13.webvpn.ecut.edu.cn/jwglxt/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005&su=${stu}`

//   // 构造POST数据
//   let postData = {
//     xnm: xn,
//     xqm: xq,
//     _search: false,
//     nd: new Date(),
//     'queryModel.showCount': 100,
//     'queryModel.currentPage': 1,
//     'queryModel.sortName': '',
//     'queryModel.sortOrder': 'asc',
//     time: 1
//   }

//   let scoreData = []
//   await agent
//     .post(url)
//     .set('Content-Type', 'application/x-www-form-urlencoded')
//     .send(postData).then(function (res) {
//       // 将每条成绩数据压入数据集中
//       res.body.items.map(item => {
//         scoreData.push({
//           'score': item.bfzcj,    //百分制成绩
//           'credit': item.xf,           //学分
//           'jd': item.jd,           //绩点
//           'coursenature': item.kcxzmc,   //课程性质
//           'coursename': item.kcmc,       //课程名称  
//           'courseid':item.kch    //课程号
//         })
//       })
//     })
//   return scoreData
// }
async function getScore(agent, stu, xn, xq) {
  console.log('成绩爬取开始...')
  const url = `https://172-20-130-13.webvpn.ecut.edu.cn/jwglxt/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005&su=${stu}`

  // 构造POST数据
  let postData = {
    xnm: xn,
    xqm: xq == 1 ? 3 : 12,
    _search: false,
    nd: new Date(),
    'queryModel.showCount': 100,
    'queryModel.currentPage': 1,
    'queryModel.sortName': '',
    'queryModel.sortOrder': 'asc',
    time: 1
  }

  let scoreData = []
  await agent
    .post(url)
    .set('Content-Type', 'application/x-www-form-urlencoded')
    .send(postData).then(function (res) {
      // 将每条成绩数据压入数据集中
      res.body.items.map(item => {
        scoreData.push({
          'sno': stu,
          'courseid': item.kch,    //课程号
          'coursename': item.kcmc,       //课程名称  
          'coursenature': item.kcxzmc,   //课程性质
          'credit': item.xf,           //学分
          'score': item.bfzcj,    //百分制成绩
          'jd': item.jd,           //绩点
          'xn': xn,
          'xq': xq
        })
      })
    })
  console.log('数据爬取结束:')
  return scoreData
}

async function getPowerRate(agent, stu) {

  let result = {}

  const sysLoginUrl = 'https://authserver.ecut.edu.cn/authserver/login?service=https://ehall.ecut.edu.cn:443/qljfwapp/sys/xCardAppEcut/mobile/index.do';

  let tmpUrl = ''

  await agent.get(sysLoginUrl).then(function (res) {
    let $ = cheerio.load(res.text)
    tmpUrl = $('a')[1].attribs.href;
  })
  await agent.get(tmpUrl).then(function (res) {
    let $ = cheerio.load(res.text)
    tmpUrl = tmpUrl.substr(0, 29) + $('a')[1].attribs.href
  })

  await agent.get(tmpUrl)
  let postData = {
    userid: stu
  }
  await agent.post("https://xgwx.ecut.edu.cn:443/app/app/api/user/searchBindHouseListForMoney").set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8').send(postData).then(res => {

    let { meter_balance } = JSON.parse(res.text).data[0].meter[0];
    result = { sno: stu, powerrate: meter_balance }
  })
  console.log(result)
  return [result]

}

async function getEcard(stu, agent) {
  let result = {}
  const getEcard = "https://cloud.life.ccb.com/commonData/queryBillsDsf.jhtml"
  await agent.post(getEcard)
    .set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
    .send(`billMerchant=1724&branNo=360000000&billItem=05013&routeFlag=500100&contract_no=${stu}&remark1=&remark2=&projectSource=07&channel=4&validateCode=`).then(function (res) {
      let { itemValue } = JSON.parse(res.text).data.displayItems[0];
      result = {
        sno: stu,
        ecard: itemValue
      }
    })
  console.log(result)
  return [result]
}

module.exports = {
  getScheduleByWeek,
  getTodayInfo,
  getStuInfo,
  getScore,
  getPowerRate,
  getEcard
}